<!-- 客户备案页 -->
<template>
  <!-- <van-popup
    v-model="show"
    position="left"
    class="fa"
    :style="{ height: '100%', width: '100%' }"
  > -->
  <div>
    <!-- 引入公共头部组件:rightText="rightText" @rightEvent="onClickLeft" -->
    <HeaderMenu title="客户备案" leftText="返回" />
    <div>
      <!-- <van-empty v-show="this.data.length == 0" description="空" /> -->
      <!-- <van-contact-card type="add" @click="onClickRight" /> -->
      <!-- 备案表单内容区域 -->
      <van-form
        @submit="onSubmit"
        style="height: 100%; overflow: auto; box-sizing: border-box"
      >
        <div class="client">
          <van-field
            :rules="[{ required: true, message: '请填写客户名' }]"
            label="客户名称："
            placeholder="请输入客户名称"
            v-model="entity.cCusName"
          >
          </van-field>
          <van-field
            :rules="[{ required: true, message: '请选择省' }]"
            label="省:"
            @click="showcProvinceClick"
            v-model="entity.cProvinceName"
            placeholder="请选择省份"
            readonly
          >
          </van-field>
          <van-popup v-model="showcProvince" position="bottom">
            <van-picker
              show-toolbar
              :columns="columnscProvince"
              @confirm="cProvinceConfirm"
              @cancel="showcProvince = false"
              value-key="name"
            />
          </van-popup>
          <van-field
            :rules="[{ required: true, message: '请选择市' }]"
            label="市:"
            @click="showcCity = true"
            v-model="entity.cCityName"
            placeholder="请选择市"
            readonly
          >
          </van-field>
          <van-popup v-model="showcCity" position="bottom">
            <van-picker
              show-toolbar
              :columns="columnscCity"
              @confirm="cCityConfirm"
              @cancel="showcCity = false"
              value-key="name"
            />
          </van-popup>
          <van-field
            label="区:"
            @click="showcCounty = true"
            v-model="entity.cCountyName"
            placeholder="请选择区"
            readonly
          >
          </van-field>
          <van-popup v-model="showcCounty" position="bottom">
            <van-picker
              show-toolbar
              :columns="columnscCounty"
              @confirm="cCountyConfirm"
              @cancel="showcCounty = false"
              value-key="name"
            />
          </van-popup>

          <van-field
            label="行业分类："
            v-model="entity.cTrade"
            placeholder="请输入行业分类"
          >
          </van-field>
          <van-field
            clickable
            readonly
            name="picker"
            @click="showPicker = true"
            v-model="entity.SaleType"
            label="销售性质"
            placeholder="销售性质"
          />
          <van-popup v-model="showPicker" position="bottom">
            <van-picker
              show-toolbar
              :columns="columns"
              @confirm="onConfirm"
              @cancel="showPicker = false"
            />
          </van-popup>

          <van-field
            readonly
            @click="CustomerChoice"
            right-icon="edit"
            label="上级单位: "
            placeholder="选择上级单位"
            v-model="entity.ParentName"
          >
            <!-- <Myuser @customerChoice="Client" ref="myuser" /> -->
          </van-field>

          <van-field
            clickable
            readonly
            name="picker"
            v-model="entity.cCusTypeName"
            label="客户类型"
            placeholder="点击选择客户类型"
          />
          <!-- @click="showType = true" -->

          <van-popup v-model="showType" position="bottom">
            <van-picker
              show-toolbar
              :columns="columnsType"
              @confirm="onTypeConfirm"
              @cancel="showType = false"
              value-key="name"
            />
          </van-popup>
          <!-- <van-field
              label="客户来源："
              v-model="entity.CustomerOrigin"
            ></van-field> -->
          <van-field
            label="营业执照："
            v-model="entity.cCusRegCode"
            placeholder="请输入营业执照号码"
          ></van-field>
          <van-field
          label="手机号："
          v-model="entity.cCusPhone"
          placeholder="请输入手机号"
        ></van-field>
          <van-field
            label="开票要求："
            v-model="entity.IRInfo"
            placeholder="请输入开票要求"
          ></van-field>
          <van-field
            label="地址："
            v-model="entity.cCusAddress"
            placeholder="请输入地址"
          ></van-field>
        </div>

        <div v-show="hideshow">
          <div class="submitButton" >
            <van-button round block type="info" native-type="submit"
              >提交</van-button
            >
          </div>
        </div>
      </van-form>
    </div>

    <Myuser @customerChoice="Client" ref="myuser" />
    <!-- <Unit @customerChoice="Client" ref="unit" /> -->
    <Product @Product="Product" ref="product" />
    <Contacts :row="row" ref="contacts" />
    <!-- <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '5px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    > -->
    <!-- <van-button @click="Add" slot="button" type="info">添加</van-button> -->
    <!-- <van-button @click="close" slot="button" type="default">关闭</van-button> -->
    <!-- <van-button @click="handleSubmit" slot="button" type="primary"
        >保存</van-button
      > -->
    <!-- </div> -->
  </div>
  <!-- </van-popup> -->
</template>

<script>
import Contacts from "./contacts.vue";
import { Icon, ContactCard } from "vant";
import { Popup } from "vant";
import { AddressList } from "vant";
// 引入公共头部组件
import HeaderMenu from "../../components/VolHeaderMenu.vue";
import {
  Row,
  Col,
  Cell,
  CellGroup,
  Toast,
  NavBar,
  Divider,
  Empty,
  Pagination,
  Search,
  Sticky,
} from "vant";
import { Field } from "vant";
import PaginationCom from "../../components/PaginationCom.vue";
//客户
import Myuser from "@/components/OwnUser.vue";
import Product from "../../components/Product.vue";
export default {
  components: {
    "van-contact-card": ContactCard,
    "van-empty": Empty,
    //分割线
    "van-divider": Divider,
    "van-pagination": Pagination,
    "van-nav-bar": NavBar,
    "van-search": Search,
    "van-icon": Icon,
    "van-popup": Popup,
    "van-row": Row,
    "van-address-list": AddressList,
    "van-field": Field,
    "van-col": Col,
    "van-cell": Cell,
    "van-cell-group": CellGroup,
    "van-sticky": Sticky,
    Myuser,
    PaginationCom,
    HeaderMenu,
    Product,
    Contacts,
  },
  data() {
    return {
      // 解决表单输入移动端键盘弹起导致的页面fixed定位元素布局错乱问题
      docmHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      showHeight:
        document.documentElement.clientHeight || document.body.clientHeight,
      hideshow: true, //显示或者隐藏footer
      // 营业执照格式校验
      // cCusPhoneRules:[{
      //   required:true,
      //   message: '营业执照或手机号不能为空',
      //   trigger:blur,
      // },{
      //   validator: value => {
      //     // return (/^1[3|4|5|7|8][0-9]{9}$/ || /^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$/)
      //     return  ((/^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$/).test(value) ) || ((/^1[3|4|5|7|8][0-9]{9}$/).test(value))
      //   },
      //   message: '请输入正确的营业执照或手机号格式',
      //   trigger: 'onBlur',
      // }],
      entity: {},
      data: [],
      show: false,
      Id: "",
      row: {},
      showcProvince: false,
      showcProvince: false,
      showType: false,
      showcCounty: false,
      listChildren: [],
      showcCity: false,
      ListProvince: [],
      columnscProvince: [], //省
      columnscCity: [], //市
      columnscCounty: [], //区
      // 备案
      showType: false,
      columnsType: [
        {
          name: "备案",
          Id: -1,
        },
        {
          name: "潜在",
          Id: 0,
        },
        {
          name: "正式",
          Id: 1,
        },
        {
          name: "休眠",
          Id: 2,
        },
      ],
      columns: ["直销", "渠道", "代理"],
      // 总条数
      Total: 0,
      // 当前页数
      PageIndex: 0,
      pagination: {
        // 当前页数
        current: 1,
        // 每页条数
        pageSize: 5,
        // 总条数
        Total: 0,
        showTotal: 0,
      },
      // 存储用户信息
      info: {},
      showPicker: false,
      entity: {
        cCusTypeName: "备案客户",
      },
      obj: {},
    };
  },
  async created() {
    // 获取用户信息
    await this.Op();
  },
  watch: {
    //监听显示高度
    showHeight: function () {
      if (this.docmHeight > this.showHeight) {
        //隐藏
        this.hideshow = false;
      } else {
        //显示
        this.hideshow = true;
      }
    },
  },
  mounted() {
    //监听事件
    window.onresize = () => {
      return (() => {
        this.showHeight =
          document.documentElement.clientHeight || document.body.clientHeight;
      })();
    };
  },
  methods: {
    //新建联系人
    onClickRight() {
      this.$refs.contacts.openForm();
    },
    onEdit(id) {
      this.$refs.contacts.openForm(id);
    },
    //返回
    onClickLeft() {
      this.show = false;
    },
    //选中的产品
    Product(a) {
      console.log(a, "选择产品信息");

      this.data.push({
        ProductId: a.cInvCode,
        cInvName: a.cInvName,
        cInvCode: a.cInvCode,
        cInvStd: a.cInvStd,
      });
    },
    // 选择产品;
    Add() {
      this.$refs.product.openForm();
    },
    close() {
      this.show = false;
    },
    Client(a) {
      console.log(a);
      this.$set(this.entity, "CustomerName", a.cCusName);
      this.$set(this.entity, "ParentName", a.cCusName);
      // this.entity.CustomerName = a.cCusName;
      this.entity.ParentId = a.Id;
      // this.entity.ONOfCompany =a.ONOfCompany
    },
    //客户类型
    onTypeConfirm(value) {
      this.entity.cCusTypeName = value.name;
      this.entity.cCusType = value.Id;
      this.showType = false;
    },
    //选择客户
    CustomerChoice() {
      this.$refs.myuser.openForm();
    },

    // 省份点击事件
    showcProvinceClick() {
      this.getlist();
      // 显示省份弹窗
      this.showcProvince = true;
    },

    onConfirm(value) {
      this.entity.SaleType = value;
      this.showPicker = false;
    },

    // 获取客户列表数据
    getDataList() {
      this.selectedRowKeys = [];
      this.http
        .post(
          "/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition",
          {
            // 当前页数
            PageIndex: this.pagination.current,
            // 每页显示10条
            PageRows: 10,
            SortField: "Id",
            SortType: "asc",
            Search: this.queryParam,
          }
        )
        .then((resJson) => {
          if (resJson.Data.length == 0) {
            // 如果没有数据显示备案按钮
            this.rightText = "备案";
          } else {
            this.rightText = "";
          }
          //  计算当前总页数  用于后续对比
          let totalPage = this.pagination.current * 10;
          if (this.pagination.Total == this.pagination.current) {
            this.dataList = resJson.Data;
          } else {
            // 每页条数+5
            this.pagination.current += 1;
            // 赋值加载的总条数 用于和原始总条数做比较
            this.pagination.showTotal = totalPage;
            // 赋值总条数
            this.pagination.Total = resJson.Total;
            let arr = resJson.Data;
            // 拼接数组
            this.data = this.data.concat(arr);
          }
          // 清除加载状态
          this.loading = false;
          if (this.pagination.showTotal <= this.pagination.Total) {
            // 数据没有全部加载完成
            this.finished = false;
            this.loading = false;
          } else {
            // 数据全部加载完成
            this.finished = true;
            this.loading = false;
            // 注意，，必须return  否则接口回频繁请求
            return;
          }
        });
    },

    //获取省份信息
    getlist() {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=0", {})
        .then((resJson) => {
          this.ListProvince = resJson.Data;
          let arr = [];
          resJson.Data.forEach((item) => {
            arr.push(item.Name);
          });
          this.columnscProvince = arr;
          if (!this.flag) {
            console.log(123);
            this.getDataList();
          }
        });
    },
    //市级change
    city(e) {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=" + e, {})
        .then((resJson) => {
          this.listChildren = resJson.Data;
          this.columnscCity = resJson.Data.map((item) => {
            return item.Name;
          });
          //市
          if (this.entity.cCity) {
            let arr2 = [this.entity.cCity].reduce((pre, cur) => {
              let idx = this.listChildren.findIndex((im) => im.Id == cur);
              console.log(idx);
              pre.push(this.listChildren[idx]);
              return pre;
            }, []);
            if (arr2) {
              this.entity.cCityName = arr2[0].Name;
              this.entity.cCity = arr2[0].Id;
            }
          }
        });
    },

    //区
    village(e) {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=" + e, {})
        .then((resJson) => {
          this.listcounty = resJson.Data;
          this.columnscCounty = resJson.Data.map((item) => {
            return item.Name;
          });

          if (this.entity.cCity) {
            let arr3 = [this.entity.cCounty].reduce((pre, cur) => {
              let idx = this.listcounty.findIndex((im) => im.Id == cur);

              pre.push(this.listcounty[idx]);
              return pre;
            }, []);
            if (arr3) {
              this.entity.cCountyName = arr3[0].Name;
              this.entity.cCounty = arr3[0].Id;
            }
          }
        });
    },

    //区
    cCountyConfirm(value) {
      this.entity.cCountyName = value;

      let arr = [this.entity.cCountyName].reduce((pre, cur) => {
        let idx = this.listcounty.findIndex((im) => im.Name == cur);
        console.log(idx);
        pre.push(this.listcounty[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.entity.cCountyName = arr[0].Name;
      this.entity.cCounty = arr[0].Id;

      this.showcCounty = false;
    },
    //市
    cCityConfirm(value) {
      this.entity.cCityName = value;

      let arr = [this.entity.cCityName].reduce((pre, cur) => {
        let idx = this.listChildren.findIndex((im) => im.Name == cur);
        console.log(idx);
        pre.push(this.listChildren[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.entity.cCityName = arr[0].Name;
      this.entity.cCity = arr[0].Id;
      this.village(this.entity.cCity);
      this.showcCity = false;
    },
    //省
    cProvinceConfirm(value) {
      console.log(value);
      this.entity.cProvinceName = value;

      let arr = [this.entity.cProvinceName].reduce((pre, cur) => {
        let idx = this.ListProvince.findIndex((im) => im.Name == cur);
        console.log(idx);
        pre.push(this.ListProvince[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.entity.cProvinceName = arr[0].Name;
      this.entity.cProvince = arr[0].Id;
      this.city(this.entity.cProvince);
      this.showcProvince = false;
    },

    // 备案提交
    onSubmit(values) {
      var that = this;
      this.entity.cCusType = -1;

      this.http
        .post("/CustomerManagement/CustomerInfo/SaveData", this.entity)
        .then((resJson) => {
          this.loading = false;
          if (resJson.Success) {
            // Toast.success("操作成功");
            console.log(this.info);
            let obj = {};
            obj.CustomerId = resJson.Data.Id;
            obj.CustomerName = resJson.Data.cCusName;
            obj.Id = null;
            obj.SalesmanId = this.info.Id;
            obj.SalesmanName = this.info.RealName;
            obj.ApprovalStatus = resJson.Data.cCusType;
            obj.ApplyDate = resJson.Data.CreateTime;
            obj.Type = "3";
            console.log(obj);
            this.obj = obj;
            that.AddRecord(obj);
          } else {
            Toast(resJson.Msg);
          }
        });
    },

    AddRecord(obj) {
      this.http
        .post("/CustomerManagement/Cust_CustomerApply/SaveData", obj)
        .then((res) => {
          if (res.Success) {
            Toast.success("备案成功");
            // 返回上一页
            this.$router.back()
            // this.getDataList();
          } else {
            Toast.success(res.Msg);
          }
        });
    },

    // 获取用户信息
    async Op() {
      await this.http.post("/Base_Manage/Home/GetOperatorInfo").then((res) => {
        if (res.Success) {
          this.info = res.Data.UserInfo;
          console.log(this.info);
          // this.$message.success('操作成功')
        } else {
          this.$message.error(res.Msg);
        }
      });
    },

    init() {
      this.show = true;
      (this.data = []), (this.entity = {});
    },

    openForm(row) {
      this.init();
      this.row = row;
      // console.log(row);
      if (row) {
        this.Id = row.Id;
        this.getDataList();
      }
    },
  },
};
</script>

<style>
.scrollBar {
  height: 550px;
  overflow: auto;
}
.close {
  position: "absolute";

  right: 0;
  bottom: 0;
  padding: "5px 16px";
  background: "#fff";
  text-align: right;
  z-index: 1;
}
.client {
  box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 5px 5px;
}
.Editbox {
  width: 80%;
  height: 80px;
  overflow: auto;
  margin: 0 auto;

  border: 1px solid #ccc;

  margin-top: 20px;
  margin-bottom: 10px;
}
/* .Father {
  display: flex;
} */
</style>
